<template>
    <div class="family-info" >
        <!-- tabs栏 -->
        <el-tabs v-model="editableTabsValue" type="card" :class="{unEdit: !editable, mas6: familyList.length >= 6}" editable @edit="handleTabsEdit">
            <el-tab-pane :key="item.name" v-for="(item, index) in editableTabs" :label="item.title" :name="item.name">
            </el-tab-pane>
        </el-tabs>

        <!-- 主体信息 -->
        <div class="info-main">
            <ul class="clear">
                <li ref="member" v-for="(member,idx) in familyList" :key="idx" :class="{unEdit: !editable, active: idx==currentIdx,bigger:(currentIdx==idx-1 && currentIdx%2==0 )}">
                    <el-form label-width="150px" label-position="left" class="demo-ruleForm clear">
                        <template v-if="member.user_id!==0">
                            <el-form-item :label="'家长'+(idx + 1)+'账号'" >
                                <el-input v-model="member.number" disabled></el-input>
                            </el-form-item>
                            <el-form-item label="用户名" >
                                <el-input v-model="member.username" disabled></el-input>
                            </el-form-item>
                        </template>
                        <template v-for="(item,key) in member.field">
                            <!-- type==1 input框 -->
                            <el-form-item v-if="item.type === 1" :label="item.field_name" :key="key" >
                                <el-input v-model="item.content.content" @change.native="initValue(item)" :placeholder="'请输入'+item.field_name" :disabled="!editable"></el-input>
                            </el-form-item>
                           
                            <!-- type==3 radio(如：男、女) -->
                            <el-form-item v-if="item.type === 3" :label="item.field_name" :key="key" >
                                <el-radio-group v-model="item.content.content" :disabled="!editable">
                                    <el-radio v-for="(item2, key2) in item.field_option" :label="key2 + 1 + ''" :key="key2">{{item2}}</el-radio>
                                </el-radio-group>
                            </el-form-item>

                            <!-- type==4 时间型 -->
                            <el-form-item v-if="item.type === 4" :label="item.field_name" :key="key" >
                                <el-date-picker
                                    v-model="item.content.content"
                                    type="date"
                                    :disabled="!editable"
                                    placeholder="选择日期"
                                    format="yyyy-MM-dd"
                                    value-format="yyyy-MM-dd">
                                </el-date-picker>
                            </el-form-item>

                            <!-- type==5 下拉窗 -->
                            <el-form-item v-if="item.type === 5" :label="item.field_name" :key="key" >
                                <el-select v-model="item.content.content" :placeholder="'请选择' + item.field_name" :disabled="!editable">
                                    <el-option
                                        v-for="(item3, key3) in item.field_option"
                                        :key="key3"
                                        :label="item3"
                                        :value="item3">
                                    </el-option>
                                </el-select>
                            </el-form-item>

                            <!-- type==6 textarea -->
                            <el-form-item v-if="item.type === 6" :label="item.field_name" :key="key" >
                                <el-input type="textarea" v-model="item.content.content" @change.native="initValue(item)" :placeholder="'请选择' + item.field_name" maxlength="50" show-word-limit :disabled="!editable"></el-input>
                            </el-form-item>
                        </template>
                        <template v-if="((idx%2 === 0  && member.user_id===0) && ( familyList.length>=idx+2 && familyList[idx+1].user_id > 0  )) || ((idx%2 === 1  && member.user_id===0) && familyList[idx-1].user_id > 0  )">
                            <el-form-item label="  " class="zanwei">
                                <el-input></el-input>
                            </el-form-item>
                            <el-form-item label="  " class="zanwei">
                                <el-input></el-input>
                            </el-form-item>
                        </template>
                    </el-form>
                </li>
            </ul>
        </div>
    </div>
</template>

<script>
    export default{
        props:['editable'],
        data(){
            return {
                editableTabsValue: '',     // 当前焦点的tabs的name
                editableTabs: [],      // tabs的数组
                familyList: [], // 家庭信息
                FamilyList: [], // 默认家庭信息
            }
        },
        created() {
            // 获取表单信息
            this.getList();
        },
        methods: {
            // 若非编辑状态下的报错
            notEdit(){
                this.$message.warning('目前是非编辑状态');
            },
            // tab排序
            sore(arr){
                this.editableTabs = [];

                // tabs栏
                var jiazhang = 1,chengyuan =1;
                arr.forEach((item,idx)=>{
                    if(item.user_id!==0){
                        this.editableTabs.push(
                            {
                                title: '家长 ' + (jiazhang),
                                name: '家长 ' + (jiazhang++),  
                            }
                        )
                    }else{
                        this.editableTabs.push(
                            {
                                title: '成员 ' + (chengyuan),
                                name: '成员 ' + (chengyuan++),  
                            }
                        )
                    }
                })
            },
            /**
             * 获取信息
             * @param {Number} key 1基础信息 || 2家庭信息 || 3来源信息 || 4其他信息
             */
            getList() {
                let success = (res => {
                    this.sore(res.data);

                    if(this.editableTabs.length > 0){
                        this.editableTabsValue = this.editableTabs[0].name;
                    }

                    // 成员消息板块
                    this.familyList = deep_clone(res.data);
                    this.FamilyList = deep_clone(res.data);
                    // console.log(this.familyList)
                    this.familyBindLen = this.familyList.filter(item => item.user_id !== 0).length;
                });
                let params = {
                    user_id: this.$g.user_id,
                    from_type: 2,
                }
                
                this.$ajax.get('api/studystatus/studystatus_info', {params, func: {success: success}})
            },
            // 初始化输入框的值
            initValue(a){
                if(a.content.content === ''){
                    a.content.content = null
                }
            },
            // tabs成员新增或者删除item都会触发
            handleTabsEdit(targetName, action) {
                if(!this.editable){
                    this.notEdit()
                    return
                }

                // 邢增tab的操作
                if (action === 'add') {
                    if(this.familyList.length > this.FamilyList.length){
                        this.$message.warning('每次只能添加一个成员');
                        return    
                    }

                    if(this.familyList.length >= 6){
                        this.$message.warning('最多只能添加6个成员');
                        return    
                    }

                    if(this.editableTabs.length==0){
                        this.editableTabs.push({
                            title: '成员 1',
                            name: '成员 1',
                        });
                    }else{
                        var lastChild = this.editableTabs[this.editableTabs.length-1].name;     // 要兼容没有绑定家长和成员的情况
                        var lastIdx = lastChild.slice(3) - 0;      // 家长或成员的最后编号
                        var lastName = lastChild.slice(0,3);     // tabs的名称（家长或成员）
                        // console.log(lastName,lastIdx)

                        if(lastName=='成员 '){
                            var newTabName = lastName + (lastIdx+1)
                        }else{
                            var newTabName = '成员 1'
                        }

                        this.editableTabs.push({
                            title: newTabName,
                            name: newTabName,
                        });

                    }

                    // 添加新成员的信息模板
                    this.newMember();

                    this.editableTabsValue = newTabName;

                }

                // ------------------------------删除为做----------------------------------------------

                // 删除tab的操作
                if (action === 'remove') {
                    let yes = (res => {
                        this.removeMenber(targetName)
                    })
                    let cancel = (res => {})
                    
                    this.e_confirm({yes: yes, cancel: cancel, txt: '是否删除当前家庭成员模块？'});

                }
            },
            /**
             * 删除新增成员
             */
            removeMenber(targetName) {
                let tabs = this.editableTabs;
                let activeName = this.editableTabsValue;
                if (activeName === targetName) {
                    tabs.forEach((tab, index) => {
                        if (tab.name === targetName) {
                            let nextTab = tabs[index + 1] || tabs[index - 1];
                            if (nextTab) {
                                activeName = nextTab.name;
                            }
                        } 
                    });
                }
              
                // 遍历出当前删除成员在成员数组中的索引值，然后在删除
                var deleteIdx;
                this.editableTabs.forEach((item,idx)=>{
                    if(item.name==targetName){
                        deleteIdx = idx;
                    }
                });

                this.editableTabsValue = activeName;
                this.editableTabs = tabs.filter(tab => tab.name !== targetName);
                
                this.familyList.splice(deleteIdx,1)

                // tab重新排序
                this.sore(this.familyList);
            },
            /**
             * 家庭信息 -- 添加新成员
             */
            newMember() {
                this.familyList.push({
                    number: '',
                    user_id: 0,
                    username: '',
                    field: [
                       {id: 19, field_name: '真实姓名', field_option: '', type: 1, content: {content: null}},
                       {id: 20, field_name: '关系', field_option: '', type: 1, content: {content: null}},
                       {id: 21, field_name: '是否监护人', field_option :['是', '否'], 'type': 3, content: {content: null}},
                       {id: 22, field_name: '电话', field_option: '', type: 1, content: {content: null}},
                       {id: 23, field_name: '职务', field_option: '', type: 1, content: {content: null}},
                       {id: 24, field_name: '单位地址', field_option: '', type: 1, content: {content: null}},
                       {id: 25, field_name: '国籍', field_option: '', type: 1, content: {content: null}},
                       {id: 26, field_name: '民族', field_option: '', type: 1, content: {content: null}},
                       {id: 27, field_name: '籍贯', field_option: '', type: 1, content: {content: null}},
                       {id: 28, field_name: '户籍所在地', field_option: '', type: 1, content: {content: null}},
                       {id: 50, field_name: '身份证号', field_option: '', type: 1, content: {content: null}}
                    ] 
                })
            },
            // 表单验证
            submitForm(formName) {
                // console.log('familyList:',this.familyList)
                // console.log('FamilyList:',this.FamilyList)

                // let len1 = this.errorTitle1.length;
                // if (len1 > 0) {
                //     for (let i=0; i<len1; i++) {
                //         if (this.errorTitle1[i] !== '') {
                //             return false;
                //         }
                //     }
                // }

                // let len2 = this.errorTitle2.length;
                // if (len2 > 0) {
                //     for (let i=0; i<len2; i++) {
                //         if (this.errorTitle2[i] !== '') {
                //             return false;
                //         }
                //     }
                // }

                let param = {arr: []};
                param.arr['user_id'] = this.$g.user_id;
                param.arr['family'] = [];

                this.familyList.forEach((item, index) => {
                    param.arr['family'][index] = [];
                    param.arr['family'][index]['family_id'] = item.user_id;

                    item.field.forEach(item1 => {
                        param.arr['family'][index].push({
                            field_id: item1.id,
                            content: item1.content.content
                        })
                    })
                })

                const success = (res => {
                    let status;
                    if(res.status == 'success'){
                        status = true;

                        // 更新表单信息
                        this.getList();
                    }else{
                        status = false;
                    }

                    this.$emit('changeSaveStatus', status)
                })

                this.$ajax.post("api/studystatus/studystatus_operation", param, {func: {success: success}});
            },
            // 检测当前板块有没有修改
            contrast(){
                // console.log('familyList:',JSON.stringify(this.familyList) == JSON.stringify(this.FamilyList))
                // console.log('familyList:',deep_clone(this.familyList), deep_clone(this.FamilyList))
                return JSON.stringify(this.familyList) == JSON.stringify(this.FamilyList)
            },
            // 取消编辑
            cancelEdit(){
                this.familyList = deep_clone(this.FamilyList);
                this.sore(this.familyList)
            },
        },
        computed:{
            currentIdx(){
                var active;
                this.editableTabs.forEach((item,idx)=>{
                    if(item.name==this.editableTabsValue){
                        active = idx;
                    }
                })
                return active;
            }
        }
    }
</script>
<style lang="scss">
    .family-info{
        // tabs栏
        .el-tabs.el-tabs--card.el-tabs--top{
            .el-tabs__header.is-top{
                border: 1px solid #DDDDDD;

                .el-tabs__new-tab{
                    margin: 10px 10px 10px 10px;
                    width: auto;
                    height: 20px;
                    line-height: 20px;
                    font-size: 14px;
                    border: 0 none;

                    .el-icon-plus{
                        transform: scale(1,1);

                        &::before{
                            content: '添加新成员';
                            font-size: 14px;
                            color: #348EFC;
                            letter-spacing: 0;
                            text-align: center;
                        }

                    }

                }

                .el-tabs__nav-wrap.is-top{
                    height: auto;
                    margin-bottom: 0;

                    .el-tabs__nav-scroll{
                        height: 40px;

                        .el-tabs__nav.is-top{
                            border: 0 none;

                            .el-tabs__item{
                                margin-top: -2px;
                                border-bottom: 0 none;

                                &:last-child{
                                    border-right: 1px solid #E4E7ED;
                                }

                                &.is-active{
                                    position: relative;
                                    top: 2px;
                                    color: #303133;
                                    border: 2px solid #348EFC;
                                }

                                // 关闭图标样式
                                .el-icon-close{
                                    background: url('../../../assets/images/schoolroll/移除.png') center center no-repeat;
                                    background-size: 14px 14px;
                                    top: -1px;
                                    right: -10px;

                                    &::before{
                                        content: '';
                                        transform: scale(1);
                                    }

                                }

                            }

                        }

                    }

                }

            }

        }

        .unEdit{
            .el-tabs__item.is-active{
                border-top: 0 none !important;
                border-right: 0 none !important;
                border-bottom: 0 none !important;
                border-left: 1px solid #E4E7ED !important;
            }

            .el-icon-close{
                display: none;
            }

        }

        .mas6 .el-tabs__new-tab{
                display: none;
        }

        // 主题信息
        .info-main{
            >ul{
                >li{
                    box-sizing: border-box;
                    margin-bottom: 20px;
                    padding: 26px 35px 0;
                    // height: 810px;
                    width: 540px;
                    background: #F6F8FA;

                    &:nth-child(odd){
                        float: left;
                    }

                    &:nth-child(even){
                        float: right;

                        &.bigger{
                            margin-bottom: 24px;
                        }

                    }
                    
                    .zanwei{
                        visibility: hidden;
                    }
                    
                    &.active{
                        border: 2px solid #348EFC;
                    }
                    
                    &.active.unEdit{
                        border: 0 none;
                    }

                    // 表单
                    .el-form{
                        >.el-form-item{
                            width: auto !important;
                            
                            .el-form-item__label{
                                padding: 0;
                                font-size: 14px;
                                color: #333333;
                                letter-spacing: 0.08px;
                                
                                &::before{
                                    content: ''
                                }
                                
                            }
                            
                            .el-form-item__content{
                                // 单选框
                                .el-radio-group{
                                    .el-radio{
                                        .el-radio__input{
                                            .el-radio__inner:hover{
                                                border-color: #3bb;
                                            }
                                            
                                        } 
                                        
                                    }
                                    

                                    // 被选中后的样式
                                    .el-radio.is-checked{
                                        .el-radio__input.is-checked{
                                            .el-radio__inner{
                                                border-color: #3bb;
                                                background: #3bb;
                                                
                                                &:hover{
                                                    border-color: #3bb;
                                                }

                                            }

                                        } 

                                        .el-radio__label{
                                            color: #606266;
                                        }

                                    }

                                }
                                
                                // input框不可编辑时的样式
                                .el-input.is-disabled{
                                    .el-input__inner{
                                        color: #333;
                                        border-radius: 0;
                                        background-color: #EFEFEF;
                                        border-color: #DDDDDD;
                                    }

                                }

                            }

                        }

                    }

                }

            }

        }

    }
</style>